<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>购物车</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="./static/css/font.css">
    <link rel="stylesheet" href="./static/css/xadmin.css">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="./static/lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="./static/js/xadmin.js"></script>
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        .layui-table-cell {
            text-align: center;
            height: auto;
            white-space: normal;
        }
    </style>
</head>

<body class="layui-anim layui-anim-up">
<input name="tableId" id="tableId" type="hidden" value="${param.tableId}">
<input name="orderId" id="orderId" type="hidden">
<div class="x-body">


    <table class="layui-table" lay-filter="action" id="data-table"></table>
    <xblock>
        <button class="layui-btn layui-btn-danger" id="delete-all" data-type="getCheckRows"><i class="layui-icon"></i>批量删除
        </button>
        <div class="layui-inline" style="float:right">
            <span>订单总价：<span id="orderMoney" style="color: red">0</span>元</span>
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1" STYLE="margin-left: 20px">提交订单</button>
        </div>
    </xblock>

</div>
<script>
    layui.use(['table', 'form'], function () {
        $ = layui.jquery;
        var form = layui.form;
        // 数据表格
        var table = layui.table;

        // 获取当前餐桌的订单id
        $.ajax({
            async: false,
            type: "post",
            url: "${pageContext.request.contextPath}/foreground?m=findOrderIdByTableID",
            dataType: "json",
            data: {tableId: $("#tableId").val()},
            success: function (data) {
                if (data.code === 200) {
                    $('#orderId').val(data.data);
                }
            }
        });

        //第一个实例
        var tableIns = table.render({
            elem: '#data-table'
            , height: 530
            , url: "${pageContext.request.contextPath}/foreground?m=findOrderByTableId&tableId=" + $("#tableId").val()
            , cols: [[ //表头
                {type: 'checkbox'}
                , {
                    field: 'foodId', title: '编号', style: 'display:none;', templet: (function (d) {
                        return d.orderFood.food.foodId;
                    })
                }
                , {
                    field: 'foodCountBk', title: '菜品数量备份', style: 'display:none;', templet: (function (d) {
                        if (d.orderFoodBk == null) {
                            return '0';
                        } else {
                            return d.orderFoodBk.foodCountBk;
                        }
                    })
                }
                , {
                    field: 'foodName', title: '菜品名', width: 165, templet: (function (d) {
                        return d.orderFood.food.foodName;
                    })
                }
                , {
                    field: 'foodCount', title: '菜品数量', width: 125, templet: (function (d) {
                        return d.orderFood.foodCount;
                    })
                }
                , {
                    field: 'foodPrice', title: '菜品单价', width: 125, templet: (function (d) {
                        return d.orderFood.foodPrice + "元";
                    })
                }
                , {
                    field: 'foodMoney', title: '单项总价', width: 125, templet: (function (d) {
                        var orderMoney = parseFloat($('#orderMoney').text());
                        $('#orderMoney').text(orderMoney + d.orderFood.foodMoney);
                        return d.orderFood.foodMoney + "元";
                    })
                }
                , {title: '操作', width: 200, toolbar: "#editTool"}
                , {title: '删除', width: 110, toolbar: "#deleteTool"}
            ]]
        });


        $('table.layui-table thead tr th:eq(1)').addClass('layui-hide');
        $('table.layui-table thead tr th:eq(2)').addClass('layui-hide');


        //监听工具条
        table.on('tool(action)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

            if (layEvent == 'del') {
                if (data.orderFoodBk != null) {
                    layer.msg("不能删除已下单的菜品！");
                    return;
                }
                layer.confirm('真的删除行么', function (index) {
                    // 发送ajax 去删除数据
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath}/foreground?m=deleteOrderFood&orderId=" + $("#orderId").val(),
                        data: {ids: [data.orderFood.foodId]},
                        dataType: "json",
                        success: function (data) {
                            if (data.code === 200) {
                                // 数据重载
                                $('#orderMoney').text(0);
                                tableIns.reload();
                                $('table.layui-table thead tr th:eq(1)').addClass('layui-hide');
                                $('table.layui-table thead tr th:eq(2)').addClass('layui-hide');

                            }
                            layer.close(index);
                        }
                    });

                });
            } else if (layEvent == 'sub') {
                var foodCountBk = 0;
                if (data.orderFoodBk !=null){
                    foodCountBk = parseInt(data.orderFoodBk.foodCountBk);
                }
                var foodCount = parseInt(data.orderFood.foodCount);
                if (foodCount <= foodCountBk) {
                    layer.msg("不能取消已下单的菜品！");
                    return;
                }
                // 将数据传递到后台
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath}/foreground?m=subOrderFood",
                    dataType: "json",
                    data: {
                        orderFoodId: data.orderFood.orderFoodId,
                        foodId: data.orderFood.foodId,
                        foodCount: foodCount
                    },
                    success: function (jsonData) {
                        if (jsonData.code === 200) {
                            // 数据重载
                            $('#orderMoney').text(0);
                            tableIns.reload();
                            $('table.layui-table thead tr th:eq(1)').addClass('layui-hide');
                            $('table.layui-table thead tr th:eq(2)').addClass('layui-hide');
                        }
                    }
                });
            } else if (layEvent == 'add') {
                var foodCount = parseInt(data.orderFood.foodCount);
                // 将数据传递到后台
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath}/foreground?m=addOrderFood",
                    dataType: "json",
                    data: {
                        tableId:$("#tableId").val(),
                        foodId: data.orderFood.foodId,
                        foodCount: foodCount
                    },
                    success: function (jsonData) {
                        if (jsonData.code === 200) {
                            // 数据重载
                            $('#orderMoney').text(0);
                            tableIns.reload();
                            $('table.layui-table thead tr th:eq(1)').addClass('layui-hide');
                            $('table.layui-table thead tr th:eq(2)').addClass('layui-hide');

                        }
                    }
                });
            }
        });


        var $ = layui.$, active = {
            getCheckRows: function () { //获取选中数据
                var checkStatus = table.checkStatus('data-table')
                    , data = checkStatus.data;
                // 检测个数
                if (data.length === 0) {
                    layer.msg("至少选中一个!");
                    return;
                }

                var canDelete = true;
                $(data).each(function () {
                    if (this.orderFoodBk != null) {
                        layer.msg("不能删除已下单的菜品！");
                        canDelete = false;
                    }
                });
                if (!canDelete) {
                    return;
                }

                layer.confirm('确定批量删除吗?', function (index) {
                    // 获取id
                    var ids = [];
                    $(data).each(function () {
                        ids.push(this.orderFood.foodId);
                    });

                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath}/foreground?m=deleteOrderFood&orderId=" + $("#orderId").val(),
                        data: {ids: ids},
                        dataType: "json",
                        success: function (data) {
                            if (data.code === 200) {
                                // 数据重载
                                $('#orderMoney').text(0);
                                tableIns.reload();
                                $('table.layui-table thead tr th:eq(1)').addClass('layui-hide');
                                $('table.layui-table thead tr th:eq(2)').addClass('layui-hide');

                            }
                            layer.close(index);
                        }
                    });
                });
            }
        };

        $('#delete-all').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //监听提交
        form.on('submit(demo1)', function (data1) {
            layer.confirm('确认提交订单吗?', function (data) {
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath}/foreground?m=submitOrder",
                    dataType: "json",
                    data: {
                        orderId:$("#orderId").val(),
                        orderMoney:$("#orderMoney").text()
                    },
                    success: function (jsonData) {
                        layer.msg(jsonData.msg, function () {
                            if (jsonData.code === 200) {
                                window.parent.location.reload();
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            }
                        });

                    }
                });
            });
        });
    });

</script>

<%--删除操作的列--%>
<script type=“text/html” id="deleteTool">
      <a class="layui-btn layui-btn-danger layui-btn-xs"  lay-event="del"><i class="layui-icon">&#xe640;</i>删除</a>


</script>

<%--编辑操作的列--%>
<script type=“text/html” id="editTool">
        <a class="layui-btn layui-bg-red layui-btn-xs" lay-event="sub">✖ 取消一份</a>
      <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add">✚ 再来一份</a>

</script>
</body>

</html>